<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Arrow Key Listener</title>
    <style>
      #a1 {
        width: 50px;
        height: 50px;
        background-color: rgb(27, 27, 28);
        position: absolute;
        top: 50px;
        left: 50px;
      }
    </style>
    <script>
      document.addEventListener("keydown", function (event) {
        var div = document.getElementById("a1");
        var currentTop = parseInt(window.getComputedStyle(div).top, 10);
        var currentLeft = parseInt(window.getComputedStyle(div).left, 10);

        switch (event.key) {
          case "ArrowUp":
            console.log("Up arrow key pressed");
            var newTop = currentTop - 10;
            if (newTop >= 0) {
              div.style.top = newTop + "px";
            }
            break;
          case "ArrowDown":
            console.log("Down arrow key pressed");
            var newTop = currentTop + 10;
            // 防止div移出窗口底部（可选，这里未实现）
            if (newTop + div.offsetWidth <= window.innerHeight) {
              //offsetWidth为方块width
              div.style.top = newTop + "px";
            }
            break;
          case "ArrowLeft":
            console.log("Left arrow key pressed");
            var newLeft = currentLeft - 10;
            if (newLeft >= 0) {
              div.style.left = newLeft + "px";
            }
            break;
          case "ArrowRight":
            console.log("Right arrow key pressed");
            var newLeft = currentLeft + 10;
            // 防止div移出窗口右侧
            if (newLeft + div.offsetWidth <= window.innerWidth) {
              div.style.left = newLeft + "px";
            }
            break;
        }
      });
    </script>
  </head>
  <body>
    <div id="a1"></div>
    <!-- 页面内容 -->
  </body>
</html>
